//
//  NewPictureManageViewController.m
//  QXShowing
//
//  Created by 王道道 on 2018/5/12.
//  Copyright © 2018年 doll_dream. All rights reserved.
//

#define kCellWidth (App_Frame_Width - (15*5))/4

#import "NewPictureManageViewController.h"

#import "RefreshCollectionView.h"
#import "UIViewController+BHMediaExt.h"
#import "TZImagePickerController.h"

#import "MyPicCollectionViewCell.h"

#import "MyPicModel.h"

static NSString *const cellId = @"listCell";

@interface NewPictureManageViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,CollectionRefreshDelegate,UICollectionViewDelegateFlowLayout,TZImagePickerControllerDelegate>
@property (nonatomic, strong) RefreshCollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, assign) BOOL isEdit;
@property (nonatomic, strong) UIButton *rightButton;

@end

@implementation NewPictureManageViewController

#pragma mark - Lazy
- (RefreshCollectionView *)collectionView {
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        _collectionView = [[RefreshCollectionView alloc]initWithFrame:CGRectMake(0, 0, App_Frame_Width, App_Frame_Height) collectionViewLayout:layout];
        _collectionView.backgroundColor = Main_BackColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.refreshDelegate = self;
        _collectionView.isRefresh = YES;
        [_collectionView registerClass:[MyPicCollectionViewCell class] forCellWithReuseIdentifier:cellId];
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}

- (NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"公司图片管理";
    [self initRightBtn];
    [self initNavBarBackBtn];
    self.isEdit = NO;
    [self.collectionView headerRefresh];
}

- (void)initRightBtn {
    _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_rightButton setFrame:CGRectMake(0, 0, 60, 44)];
    //    [rightButton setImage:[UIImage imageNamed:@"my-2"] forState:UIControlStateNormal];
    [_rightButton setTitle:@"管理" forState:UIControlStateNormal];
    [_rightButton setTitleColor:Text_Color_000000 forState:UIControlStateNormal];
    [_rightButton setBackgroundColor:[UIColor clearColor]];
    [_rightButton addTarget:self action:@selector(editAction) forControlEvents:UIControlEventTouchUpInside];
    [_rightButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:_rightButton];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)editAction {
    self.isEdit = !self.isEdit;
    if (self.dataArray.count == 0) {
        self.isEdit = NO;
    }
    [self.collectionView reloadData];
    
    if (self.isEdit == YES) {
        [_rightButton setTitle:@"删除" forState:UIControlStateNormal];
        [_rightButton setTitleColor:Text_Color_FF0000 forState:UIControlStateNormal];
    } else {
        [_rightButton setTitle:@"管理" forState:UIControlStateNormal];
        [_rightButton setTitleColor:Text_Color_000000 forState:UIControlStateNormal];
        
        //删除操作
        if (self.dataArray.count != 0) {
            [self requestPostBH_User_delCompanyPic];
        }
    }
}


- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.collectionView.frame = CGRectMake(0, 0, App_Frame_Width, CGRectGetHeight(self.view.bounds));
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
- (void)collectionView:(UICollectionView *)collectionView Refresh:(BOOL)refresh PageCount:(NSInteger)pageCount {
    [self requestPostBH_User_getCompanyPic:refresh PageCount:pageCount];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.isEdit == NO) {
        return self.dataArray.count + 1;
    } else {
        return self.dataArray.count;
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MyPicCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[MyPicCollectionViewCell alloc]init];
    }
    cell.backgroundColor = [UIColor clearColor];
    
    if (self.isEdit == NO) {
        //        if (self.dataArray.count > 0 && indexPath.row < self.dataArray.count) {
        //        }
        if (indexPath.row == self.dataArray.count) {
            cell.homeImage.image = [UIImage imageNamed:@"my-4"];
        }
        else {
            cell.model = self.dataArray[indexPath.row];
        }
        cell.chooseImage.hidden = YES;
    } else {
        cell.model = self.dataArray[indexPath.row];
        cell.chooseImage.hidden = NO;
    }

    
    cell.btnBlock = ^{
        if (self.isEdit == NO) {
            //            if (self.dataArray.count > 0 && indexPath.row < self.dataArray.count-1) {
            //            }
            if (indexPath.row == self.dataArray.count) {
                //添加图片
                [self _selectPictureCamera];
            } else {
                //查看大图
            }
        } else {
            //选中、删除
            MyPicModel *model = self.dataArray[indexPath.row];
            model.isChoose = !model.isChoose;
            if (model.isChoose) {
                cell.chooseImage.image = [UIImage imageNamed:@"my-7"];
            } else {
                cell.chooseImage.image = [UIImage imageNamed:@"my-6"];
            }
        }
    };
    
    return cell;
}

#pragma mark ---- UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(kCellWidth, kCellWidth);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(20, 15, 20, 15);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
//    ShowViewController *next = [[ShowViewController alloc] init];
//    HomeShowModel *model = self.dataArray[indexPath.item];
//    next.Id = model.Id;
//    [self pushViewController:next animated:YES];
}

#pragma mark -
- (void)_selectPictureCamera {
    [UIViewController showAlertWithTitle:nil message:nil actionTitles:@[@"相册"] cancelTitle:@"取消" style:UIAlertControllerStyleActionSheet completion:^(NSInteger index) {
        if (index == 0) {
            TZImagePickerController *imagePickController = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
            imagePickController.allowPickingVideo = NO;
//            imagePickController.selectedAssets = self.assetsArray;
            [self presentViewController:imagePickController animated:YES completion:nil];
//            [self.navigationController presentViewController:self.imagePickerController animated:YES completion:nil];
        }
    }];
}

#pragma mark - TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
//    [self.imageArray removeAllObjects];
//    [self.assetsArray removeAllObjects];
//    [self.imageArray addObjectsFromArray:photos];
//    [self.assetsArray addObjectsFromArray:assets];
//    [self.collectionView reloadData];
    
    [self requestPostBH_User_addCompanyPic:photos[0]];
}


- (void)_loadData:(id)response Refresh:(BOOL)refresh {
    if (refresh) [self.dataArray removeAllObjects];
    NSArray *arr = [NSArray yy_modelArrayWithClass:[MyPicModel class] json:response];
//    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
//    for (int i = 0; i < arr.count; i++) {
//        MyPicModel *model = arr[i];
//        model.isChoose = NO;
//        [tempArray addObject:model];
//    }
//    [self.dataArray addObjectsFromArray:tempArray];

    [self.dataArray addObjectsFromArray:arr];
    if (arr.count < 10) {
        [self.collectionView endRefreshingWithNoMoreData];
    }
    [self.collectionView reloadData];
}

- (void)requestPostBH_User_getCompanyPic:(BOOL)refresh PageCount:(NSInteger)pageCount {
    SGUserModel *userModel = [SGUserInfo getUserInfo];
    
    self.dataArray.count != 0 ?: [[BHAlertUtil alertManager]showLoadingView:self.view];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    //    [params setObject:@"" forKey:@"uid"];
    //    [params setObject:@"14" forKey:@"company_id"];
    
    if (![BHSettingUtil dataAndStringIsNull:userModel.company_id]) {
        [params setObject:userModel.company_id forKey:@"company_id"];
    }
    else if (![BHSettingUtil dataAndStringIsNull:userModel.Id]) {
        [params setObject:userModel.Id forKey:@"uid"];
    }
    else {
        
    }

    [params setObject:[NSString stringWithFormat:@"%ld",(long)pageCount] forKey:@"page"];
    [params setObject:@"10" forKey:@"pagesize"];
    
    [PPHTTPRequest requestPostBH_User_getCompanyPic:^(id response, BOOL success) {
        if (self.dataArray.count == 0 && [response isKindOfClass:[NSString class]]) {
            //            self.collectionView.placeholderShow(YES).prompt_title((NSString *)response).isButtonHidden(YES);
        }else self.collectionView.placeholderShow(NO);
        if (success && ![response isKindOfClass:[NSString class]]) {
            [self _loadData:response Refresh:refresh];
        }
        if (success && refresh == YES) {
            [self _loadData:response Refresh:refresh];
        }
        [[BHAlertUtil alertManager]hiddenLoading];
    } params:params];
}

//添加图片
- (void)requestPostBH_User_addCompanyPic:(UIImage *)pic {
    SGUserModel *userModel = [SGUserInfo getUserInfo];

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (![BHSettingUtil dataAndStringIsNull:userModel.company_id]) {
        [params setObject:userModel.company_id forKey:@"company_id"];
    }
    else if (![BHSettingUtil dataAndStringIsNull:userModel.Id]) {
        [params setObject:userModel.Id forKey:@"uid"];
    }
    else {
        
    }
//    [params setObject:pic forKey:@"pic"];

    [PPHTTPRequest requestPostBH_User_addCompanyPic:^(id response, BOOL success) {
        if (success) {
            [self requestPostBH_User_getCompanyPic:YES PageCount:1];
        } else {
        }
    } params:params images:pic];
}

//删除图片
- (void)requestPostBH_User_delCompanyPic {
    NSString *deleteId;
    for (int i = 0; i < self.dataArray.count; i++) {
        MyPicModel *model = self.dataArray[i];
        if (model.isChoose == YES) {
            deleteId = model.Id;
            break;
        }
    }
    
    if ([BHSettingUtil dataAndStringIsNull:deleteId]) {
        
    } else {
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:deleteId forKey:@"id"];
        
        [PPHTTPRequest requestPostBH_User_delCompanyPic:^(id response, BOOL success) {
            if (success) {
                [self requestPostBH_User_getCompanyPic:YES PageCount:1];
            } else {
            }
        } params:params];
    }
    
}
@end
